$(function () {
    function loadData(startTime,endTime){
        $.ajax({
            type: "POST",
            url: "findChargeDatas",
            data: {
                "startTime": startTime,
                "endTime": endTime
            },
            timeout: 3000,
            dataType: "json",
            success: function (res) {
                if(res.datas.length!=0) {
                    parseData(res);
                }else {
                    $("#chargeChart").get(0).remove();
                    $("#chart_con").append("<h2 id='chargeChart' class='mt5'>暂无任何记录</h2>");
                }
            },
            error: function() {
                $("#chargeChart").get(0).remove();
                $("#chart_con").append("<h2 id='chargeChart' class='mt5'>数据操作有误</h2>");
            }
        });
    }
    loadData(new Date().getFullYear()-2,new Date().getFullYear()-1);

    /**
     * 解析报表数据
     * @param res 报表数据对象
     */
    function parseData(res) {
        var mydata = {
            labels: res.labels,
            datasets: [
                {
                    label: '课程总收费',
                    borderWidth: 1,
                    borderColor: 'rgba(0,0,0,0)',
                    backgroundColor: 'rgba(51,202,185,0.5)',
                    hoverBackgroundColor: "rgba(51,202,185,0.7)",
                    hoverBorderColor: "rgba(0,0,0,0)",
                    data: res.datas,
                }
            ]
        };
        $("#chargeChart").get(0).remove();
        if ($(".chartjs-size-monitor").length>0)
            $(".chartjs-size-monitor").remove();
        $("#chart_con").append("<canvas id=\"chargeChart\"></canvas>");
        var ctx = $("#chargeChart").get(0).getContext('2d');
        new Chart(ctx, {
            type: 'bar',
            data: mydata,
            options: {
                maintainAspectRatio: false,
                scales: {
                    yAxes: [{
                        ticks: {
                            display: true,
                            beginAtZero: true
                        }
                    }]
                }
            }
        });
    }

    /**
     * 时间范围限制以及报表更新
     */
    $("#startTime").change(function(){
        var $val=$("#startTime option:selected").val();
        var $max=$("#endTime option:selected").val();
        var $date = new Date().getFullYear();
        $("#endTime option").detach();
        $options = "";
        for (var i = parseInt($val)+1>=$date?$date:parseInt($val)+1; i <= $date; i++)
            $options += "<option value='" + i + "' "+(i==$max?'selected="selected"':'')+">" + i + "</option>";
        $("#endTime").html($options);
        loadData($val,$max);
    });
    $("#endTime").change(function(){
        var $val=$("#endTime option:selected").val();
        var $min=$("#startTime option:selected").val();
        loadData($min,$val);
    });

});